/***
 * Copyright (C) 2011  wexoo
 * p.weixlbaumer@gmail.com
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package net.wexoo.group_cost_calculator.dao;

import java.sql.SQLException;

import net.wexoo.group_cost_calculator.enitities.Calculation;
import net.wexoo.group_cost_calculator.enitities.CalculationMember;
import net.wexoo.group_cost_calculator.enitities.Person;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Environment;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

/**
 * DBHelper.java
 * 
 * @author wexoo
 */
public class DBHelper extends OrmLiteSqliteOpenHelper {

   /** General SQLite database information. */
   public static final String DATABASE_NAME = "group_cost_calculator";
   public static final Integer DATABASE_VERSION = 1;
   public static final String DB_PATH = Environment.getDataDirectory()
         + "/data/net.wexoo.group_cost_calculator/databases/";

   @SuppressWarnings("unused")
   private static final String TAG = DBHelper.class.getSimpleName();

   public DBHelper(final Context context) {
      super(context, DATABASE_NAME, null, DATABASE_VERSION);
   }

   /**
    * Called at the time of the first access to the db to create it
    * 
    * @author wexoo
    */
   @Override
   public void onCreate(final SQLiteDatabase db, final ConnectionSource source) {
      try {
         TableUtils.createTable(source, Calculation.class);
         TableUtils.createTable(source, Person.class);
         TableUtils.createTable(source, CalculationMember.class);
      } catch (final SQLException e) {
         e.printStackTrace();
      }
   }

   /**
    * Drop and create table.
    * 
    * @param entityClass the entity class
    */
   public void dropAndCreateTable(final Class<?> entityClass) {
      try {
         TableUtils.dropTable(getConnectionSource(), entityClass, true);
         TableUtils.createTable(getConnectionSource(), entityClass);
      } catch (final SQLException e) {
         e.printStackTrace();
      }
   }

   /**
    * Invoked if a DB upgrade (version change) has been detected.
    * 
    * @author wexoo
    */
   @Override
   public void onUpgrade(final SQLiteDatabase db, final ConnectionSource arg1,
         final int oldVersion, final int newVersion) {
      //      Toast.makeText(this, "New SQLite Version!\nPrevious: " + oldVersion + "\nNew:"
      //            + newVersion, Toast.LENGTH_LONG).show();
   }

   /**
    * Creates a empty database on the system and rewrites it with your own database.
    * 
    * @param onlineUpdate as boolean
    * @author wexoo
    * @since 1.0.0 Jul 6, 2011
    * @version 1.0.0 Jul 6, 2011
    */
   //   public void createDataBase(final boolean onlineUpdate) {
   //
   //      /*
   //       * By calling this method an empty database will be created into the
   //       * default system path
   //       * of your application so we are gonna be able to overwrite that
   //       * database with our database.
   //       */
   //      getReadableDatabase();
   //
   //      try {
   //         MigrationProxy.getInstance().storeOldFavoriteHeurige();
   //         if (onlineUpdate) {
   //            copyOnlineDataBase();
   //         } else {
   //            copyDataBase();
   //         }
   //         MigrationProxy.getInstance().importFavoriteHeurigeToNewDatabase();
   //         close();
   //      } catch (final IOException e) {
   //         throw new Error("Error copying database");
   //      }
   //   }

   /**
    * Check if the database already exist to avoid re-copying the file each
    * time you open the application.
    * 
    * @author wexoo
    */
   @SuppressWarnings("unused")
   private boolean dataBaseExists() {

      SQLiteDatabase checkDB = null;

      try {
         final String myPath = DB_PATH + DATABASE_NAME;

         checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

      } catch (final SQLiteException e) {
         return false;
      }

      if (checkDB != null) {
         checkDB.close();
      }
      return true;
   }

   /**
    * Copies your database from your local assets-folder to the just created
    * empty database in the system folder, from where it can be accessed and
    * handled. This is done by transfering bytestream.
    * 
    * @throws IOException if an input or output exception occurred
    * @author wexoo
    * @since 1.0.0 Jul 6, 2011
    * @version 1.0.0 Jul 6, 2011
    */
   //   private void copyDataBase() throws IOException {
   //
   //      Log.d(DBHelper.TAG, "starting to copy database");
   //
   //      // Open your local db as the input stream
   //      final InputStream myInput = HeurigenApp.mainContext.getAssets().open(
   //            HeurigenApp.getConfig().databaseName());
   //
   //      // Path to the just created empty db
   //      final String outFileName = DBHelper.DB_PATH + HeurigenApp.getConfig().databaseName();
   //
   //      // Open the empty db as the output stream
   //      final OutputStream myOutput = new FileOutputStream(outFileName);
   //
   //      // transfer bytes from the inputfile to the outputfile
   //      final byte[] buffer = new byte[1024];
   //      int length;
   //      while ((length = myInput.read(buffer)) > 0) {
   //         myOutput.write(buffer, 0, length);
   //      }
   //
   //      // Close the streams
   //      myOutput.flush();
   //      myOutput.close();
   //      myInput.close();
   //   }

   /**
    * Copies the online database version in the system folder
    * from where it can be accessed and handled.
    * This is done by transfering bytestream.
    * 
    * @throws IOException if the file/path is not read or writeable
    * @author naikon
    * @since 1.0.0 Jul 6, 2011
    * @version 1.0.0 Jul 6, 2011
    */
   //   private void copyOnlineDataBase() throws IOException {
   //
   //      //get http enity
   //      final HttpEntity entity = ProxyFactory.getProxy().getHttpEntity();
   //
   //      // Path to the just created empty db
   //      final String outFileName = DBHelper.DB_PATH + HeurigenApp.getConfig().databaseName();
   //
   //      // Open the empty db as the output stream
   //      final OutputStream output = new FileOutputStream(outFileName);
   //
   //      final InputStream in = entity.getContent();
   //
   //      final byte[] buffer = new byte[1024];
   //      int len1 = 0;
   //      while ((len1 = in.read(buffer)) > 0) {
   //         output.write(buffer, 0, len1);
   //      }
   //      output.close();
   //      in.close();
   //   }
}